package org.computate.controller.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.inject.Singleton;

@Singleton
public class UserFilter implements Filter {

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
		User guest = null;
		String requestURI = httpRequest.getRequestURI();
		String pageId = requestURI.replace("/", "_").replace(".", "_");
		
		if(user != null) {
			if(!user.getEmail().toLowerCase().startsWith("computating@") && !user.getEmail().toLowerCase().endsWith("@toshmd.com")) {
				guest = user;
				user = null;
			}
		}
		httpRequest.setAttribute("user", user);
		httpRequest.setAttribute("guest", guest);
		if(httpRequest.getUserPrincipal() == null || user == null && guest == null) {
			httpRequest.setAttribute("loginUrl", userService.createLoginURL(getURL(httpRequest), "toshmd.com"));
		}
		else {
			httpRequest.setAttribute("logoutUrl", userService.createLogoutURL(getURL(httpRequest), "toshmd.com"));
		}
		httpRequest.setAttribute("requestURI", requestURI);
		httpRequest.setAttribute("pageId", pageId);
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

	public static String getURL(HttpServletRequest req) {

	    String scheme = req.getScheme();             // http
	    String serverName = req.getServerName();     // hostname.com
	    int serverPort = req.getServerPort();        // 80
	    String contextPath = req.getContextPath();   // /mywebapp
	    String servletPath = req.getServletPath();   // /servlet/MyServlet
	    String pathInfo = req.getPathInfo();         // /a/b;c=123
	    String queryString = req.getQueryString();          // d=789

	    // Reconstruct original requesting URL
	    StringBuffer url =  new StringBuffer();
	    url.append(scheme).append("://").append(serverName);

	    if (serverPort != 80) {
	        url.append(":").append(serverPort);
	    }

	    url.append(contextPath).append(servletPath);

	    if (pathInfo != null) {
	        url.append(pathInfo);
	    }
	    if (queryString != null) {
	        url.append("?").append(queryString);
	    }
	    return url.toString();
	}
}
